package servlet.user.test;

import DBCP.MyDBCP;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
@WebServlet("/signin")
public class SignInServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        String selectSql = "select * from db_user.user where username = ? and password = md5(?)";
        Connection con = MyDBCP.getConnenction();
        try {
            PreparedStatement ps_select = con.prepareStatement(selectSql);
            ps_select.setString(1,username);
            ps_select.setString(2,password);
            ResultSet resultSet = ps_select.executeQuery();
            if (resultSet.next()){
                String updateSql = "update db_user.user set last_signin = ?,last_signin_ip = ? where username = ?";
                PreparedStatement ps_update = con.prepareStatement(updateSql);
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                ps_update.setString(1, sdf.format(new Date()));
                ps_update.setString(2,req.getRemoteAddr());
                ps_update.setString(3,username);
                ps_update.executeUpdate();
                req.getSession().setAttribute("username",username);
                resp.sendRedirect("Day02/user/Home_index.jsp");

            }else {
                req.getSession().setAttribute("message","check your username and password!");
                resp.sendRedirect("Day02/user/index.jsp");
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
